//
//  UITableViewController+HDMyInformation.m
//  app
//
//  Created by D on 15/4/10.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDMoreInformation.h"
#import "HDUserInforHttpRequestManger.h"
#import "HDChangeDaRenHao.h"
#import "HDChangeGender.h"
#import "UBExternal.h"
#import "HDChangeName.h"
#import "HDChangeSign.h"
#import "HDActionSheetView.h"
#import "ParticipationDataManager.h"

@implementation HDMoreInformation

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"upload"]) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"upload"];
        
        [self upLoadFace];
        
    }
    [self loadUserMore];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self loadUserMore];
    self.title = @"个人资料";
//    self.face_img.layer.masksToBounds = YES;
//    self.face_img.layer.cornerRadius = UF(6);
    self.face_faceimage.layer.masksToBounds = YES;
    self.face_faceimage.layer.cornerRadius = UF(6);
    
    self.result_logout = [JKRemoteResult target:self action:@selector(loginOut:)];
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setSeparatorColor:[UIColor clearColor]];
    
    UIImage * BGimage = [UIImage imageNamed:@"head_144.png"];
    CGFloat top = 6;
    CGFloat bottom = 6;
    CGFloat left = 6;
    CGFloat right = 6;
    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
    BGimage = [BGimage resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    [self.face_img setImage:BGimage];
}


-(void)loadUserMore
{
  
    
    self.nickNameLab.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"nickname"];
    self.gold.text = [NSString stringWithFormat:@"%@金豆",[[NSUserDefaults standardUserDefaults]objectForKey:@"gold"]];
    self.levelLab.text = [NSString stringWithFormat:@"LV%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"level"]];
//    [self.levelImg sd_setImageWithURL:[[NSUserDefaults standardUserDefaults]objectForKey:@"level_icon"]];
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"nlv_icon"] length] > 1) {
        
        [self.levelImg setImage:[UIImage imageNamed:@"forum_list_yys"]];
       

    }else
    {
        if ([[SDImageCache sharedImageCache] imageFromDiskCacheForKey:@"userLevel_icon"]) {
            [self.levelImg setImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:@"userLevel_icon"]];
        }else
        {
            [self.levelImg sd_setImageWithURL:[[NSUserDefaults standardUserDefaults]objectForKey:@"level_icon"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                NSData * data = UIImageJPEGRepresentation(image, 1.0);
                [[SDImageCache sharedImageCache] storeImage:image recalculateFromImage:YES imageData:data forKey:@"userLevel_icon" toDisk:YES];
                
            }];
            
        }

    }
    NSString * darenStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"uniqueID"];
    self.daRenHaoLab.text = darenStr.lowercaseString;
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"haveuniqueID"] integerValue] == 1) {
        [self.darenhaoCell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
//    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"edit_gender"] integerValue] == 0) {
//        [self.genderCell setSelectionStyle:UITableViewCellSelectionStyleNone];
//    }

    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"exp"] integerValue] == 0) {
        self.countLab.text = @"经验值:0";
    }else
    {
         self.countLab.text = [NSString stringWithFormat:@"经验值:%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"exp"]];
    }

    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"signature"] length] == 0) {
        self.signLab.text = @"未填写";
    }else
    {
        
             self.signLab.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"signature"];
        
        
       
    }

    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"gender"] integerValue] == 1) {
        self.genderLab.text = @"男";
    }else
    {
        self.genderLab.text = @"女";
    }
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"face"]length] == 0) {
        
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"gender"] integerValue] == 1) {
            [self.face_faceimage setImage:[UIImage imageNamed:@"isboy"]];
        }else
        {
            [self.face_faceimage setImage:[UIImage imageNamed:@"isgirl"]];
        }
        
        
    }else
    {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"headImage"]) {
            UIImage * image = [UIImage imageWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"headImage"]];
            [self.face_faceimage setImage:image];
        }else
        {
            [self.face_faceimage sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"face"]]];
        }
 
    }
    
    
    self.result_face = [JKRemoteResult target:self action:@selector(changeFace:)];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
    {       [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}



#pragma mark - 点击cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    switch (section) {
        case 0:
        {
            if (indexPath.row ==0 ) {
          
                  [self creatSheet];
  
            }else if (indexPath.row == 1)
            {
               
                    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"MainStoryBoard" bundle:nil];
                    HDChangeName * moreInfo = [storyBoard instantiateViewControllerWithIdentifier:@"name"];
                    [self.navigationController pushViewController:moreInfo animated:YES];
    
            }
            
            
        }
            break;
        case 1:
        {
            if (indexPath.row == 0) {
                self.progress_ = [[MBProgressHUD alloc]initWithView:self.view];
                [self.view addSubview:self.progress_];
                [self.view bringSubviewToFront:self.progress_];
                self.progress_.delegate = self;
                self.progress_.labelText = @"正在退出中...";
                [self.progress_ show:YES];
                
                HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
                NSDictionary * params = @{@"version":APP_VERSION};
                [httpManager loginOutWithParams:params result:self.result_logout];

            }
        }
            break;
        case 2:
        {
//            self.progress_ = [[MBProgressHUD alloc]initWithView:self.view];
//            [self.view addSubview:self.progress_];
//            [self.view bringSubviewToFront:self.progress_];
//            self.progress_.delegate = self;
////            self.progress_.labelText = @"登录中...";
//            [self.progress_ show:YES];
//            
//            HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
//            NSDictionary * params = @{@"version":APP_VERSION};
//            [httpManager loginOutWithParams:params result:self.result_logout];

        }
            break;
            
        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - section 间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 16;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}


#pragma mark - 退出账号
-(void)loginOut:(JKRemoteResult*)rt
{
    if (self.progress_) {
        [self.progress_ removeFromSuperview];
        self.progress_ = nil;
    }
    
    if (rt.failure) {
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:nil message:@"请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [self.view addSubview:av];
        [av show];
        
        return;
    }
    //    [self.navigationController setNavigationBarHidden:NO];
    
    NSString * uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uid"];
    NSString * allInformation = [[NSBundle mainBundle] bundleIdentifier];
    [[NSUserDefaults standardUserDefaults]removePersistentDomainForName:allInformation];
    
    [[SDImageCache sharedImageCache]removeImageForKey:@"user_Head"];
    
    
    
    [[NSUserDefaults standardUserDefaults] setObject:uid forKey:@"mark"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    HDAppDelegate* app = (HDAppDelegate*)[[UIApplication sharedApplication]delegate];
    
    app.storyBoard = [UIStoryboard storyboardWithName:@"LogInOutStoryboard" bundle:nil];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"userLogout"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [self.navigationController presentViewController:[app.storyBoard instantiateInitialViewController] animated:NO completion:nil];
    
//     UIViewController * loginOut = [app.storyBoard instantiateViewControllerWithIdentifier:@"login"];
//    [self.navigationController pushViewController:loginOut animated:YES];
    
}


#pragma mark - 点击头像

-(void)creatSheet
{
    HDActionSheetView *actv = [[HDActionSheetView alloc] initWithTitle:nil cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选",nil];
    actv.syActionSheetActionBlock = ^(UIButton *actionBtn){
        
        if (actionBtn.tag == kBtnCaccleTag + 1)
        {
            SYLog(@"%@",actionBtn.titleLabel.text);
            [self takePhoto];
            
        }
        else if (actionBtn.tag == kBtnCaccleTag + 2)
        {
            SYLog(@"%@",actionBtn.titleLabel.text);
            [self localPhoto];
        }
    };
    [actv showSYActionSheet];
    
}

#pragma mark - 打开照相机
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        
        [self presentViewController:picker animated:NO completion:nil];
    }else
    {

    }
}
#pragma mark - 打开相册
-(void)localPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:NO completion:nil];
}
#pragma mark - 保存图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
     UIImage *image= [info objectForKey:@"UIImagePickerControllerEditedImage"];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
    }

    [self saveImage:image WithName:@"mypic.jpg"];
    [picker dismissViewControllerAnimated:NO completion:nil];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"upload"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [self.face_img setImage:image];
    
    
}
-(UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData * imageData = UIImagePNGRepresentation(tempImage);
//    NSData * imageData = [UIImage dataOriginImage:tempImage scaleToSize:CGSizeMake(480, 480) fileToRatio:0.8];
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}
-(void)upLoadFace
{

    self.imagePath = [NSString stringWithFormat:@"%@%@",[self documentFolderPath],@"/mypic.jpg"];
    NSData * data = [NSData dataWithContentsOfFile:self.imagePath];
    
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"headImage"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    HDUserInforHttpRequestManger * httpManager = [HDUserInforHttpRequestManger shareUserInforHttpRequestManger];
    NSDictionary * params = @{@"name" : @"image",
                              @"fileName" : @"pic.jpg",
                              @"mimeType" : @"image/jpg"};
    [httpManager changeFaceWithParams:params result:self.result_face data:data];
}


#pragma mark - 更新头像
-(void)changeFace:(JKRemoteResult*)rt
{
    

    if (rt.failure) {
        
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:nil message:@"请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [self.view addSubview:av];
        [av show];
        
        return;
    }
    [[SDImageCache sharedImageCache] clearMemory];
    
    [[NSUserDefaults standardUserDefaults] setObject:[rt.content objectForKey:@"face"] forKey:@"face"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [alertView removeFromSuperview];
}

#pragma mark 从文档目录下获取Documents路径
- (NSString *)documentFolderPath
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}
@end










